{extend name="foxcms_content" /}

{block name="css"}

{/block}

{block name="body"}
<input name="bcid" value="{$bcid}" type="hidden" />
<input name="columnId" value="{$columnId}" type="hidden" />
<input name="bind_form" value="{$bind_form}" type="hidden" />
<div class="foxcms-content-inner">
	<!-- page content -->

	{if $bind_form == 0}
	<div class="company-news-content">
		<div style="text-align: center;">
			<div style="font-size: 18px;">请先绑定应用表单</div>
			<div class="section-main-item">
				<div class="foxui-input-group" style="justify-content: center;">
					<div class="input-label">
						<label>应用表单：</label>
					</div>
					<div class="input-box" style="display: flex;">
						<div class="foxui-select">
							<div class="foxui-select-handle foxui-select-icon">
								<input name="apply_form" class="foxui-select-input foxui-size-small" readonly="readonly" placeholder="请选择应用表单">
								<i class="foxui-icon-close-circle" style="display: none;"></i>
							</div>
							<div class="foxui-select-menu" x-placement="bottom-left" style="top: 6px; left: 0px; display: none;">
								<ul class="foxui-select-slide">
									{foreach $formList as $key=>$vo }
									<li class="foxui-select-item" data-id="{$vo.id}">{$vo.name}</li>
									{/foreach}
								</ul>
							</div>
						</div>
						<button class="foxui-text-primary foxui-size-small" style="margin-left: 5px;">
							<a href="{$formUrl}"><i class="foxui-icon-jiahao-o"></i>添加</a>
						</button>
					</div>
				</div>
			</div>
			<div class="section-main-item">
				<button class="is-long foxui-size-small foxui-solid-primary" id="save">保存</button>
			</div>
		</div>
	</div>
	{else/}
	<div>
		<input name="formListId" value="{$formListId}" type="hidden" />
		<input id="tableItemStr" value="{$tableItemStr}" type="hidden" />
	</div>
	<div class="diy-form-content">
		<div class="content-top-operation">
			<div class="left">

			</div>
			<div class="right display-flex">
				<div class="foxui-input-group item-input margin-right-20">
					<div class="foxui-input-prepend">
						<input class="foxui-size-small" placeholder="请输入关键字" required value="" name="keyword"/>
					</div>
				</div>
				<button class="foxui-solid-primary foxui-size-small search-btn">搜索</button>
			</div>
		</div>
		<div class="section section-panel margin-top-10">
			<div class="foxui-table foxui-table-border-bottom foxui-table-hover foxui-checkbox-group">

				<ul class="foxui-table-thead foxui-checkbox-head">
					<li class="foxui-table-tr">
						<div class="foxui-table-th" style="flex: initial; width: 40px">
							<div class="foxui-checkbox foxui-checkbox-all">
                                <span class="foxui-checkbox-input">
                                    <i class="foxui-checkbox-icon"></i>
                                    <input type="checkbox" value="" />
                                </span>
							</div>
						</div>
						<div class="foxui-table-th">ID</div>
						{foreach $tableHeads as $key=>$vo }
						<div class="foxui-table-th">{$vo.title}</div>
						{/foreach}
						<div class="foxui-table-th">操作</div>
					</li>
				</ul>

				<ul class="foxui-table-tbody foxui-checkbox-list" id="loadingContainer">

					<!--表格内容-->

				</ul>

				<div class="table-footer foxui-checkbox-head">
					<div class="left display-flex foxui-align-items-center">
						<div class="foxui-checkbox foxui-checkbox-all margin-right-24">
                            <span class="foxui-checkbox-input">
                                <i class="foxui-checkbox-icon"></i>
                                <input type="checkbox" value="" />
                            </span>
						</div>

						<div class="display-flex">
							<button class="foxui-plain-info foxui-size-mini delete-btn">
								<i class="foxui-icon-shanchu-o"></i>
								<span>删除</span>
							</button>
						</div>
					</div>
					<div class="right total">共N条记录</div>
				</div>
                <div id="pagination"></div>
			</div>

		</div>
	</div>
	{/if}


</div>

{include file="footed-copy"/}
{/block}

{block name="js"}

<script>
	$("#save").click(function () {
		//应用表单
		let form_list_id = $('input[name="apply_form"]').attr("data-id");
		if(form_list_id == undefined || form_list_id == ""){
			foxui.message({
				type:'danger',
				text:'请绑定应用表单！'
			})
			return;
		}
		let columnId = $('input[name="columnId"]').val();
		let data = {form_list_id, columnId};
		foxui.dialog({
			title: '保存',
			content: '您确定要保存吗',
			cancelText: '取消',
			confirmText: '保存',
			confirm: function (callback) {
				$.ajax({
					type: "post",
					url: "{:url('save')}",
					dataType: "json",
					data: data,
					success: function (res) {
						if (res.code == 1) {
							foxui.message({
								type:'success',
								text:res.msg
							})
							window.location.reload();
						} else {
							foxui.message({
								type:'warning',
								text:res.msg
							})
						}
					}, error: function (res) {
						foxui.message({
							type:'warning',
							text:res.msg
						})
					}
				});
				callback();
			},
			cancel: function () {
				foxui.message({
					type:'warning',
					text:'取消操作'
				})
			},
		});
	});
</script>

<script>

	let formListId = $("input[name='formListId']").val();
	/**
	 * 初始化数据
	 */
	function init(param){
		let keyword = $('input[name="keyword"]').val();
		let columnId = $('input[name="columnId"]').val();
		let searchData = {
			"keyword": keyword,
			"formListId": formListId,
			"columnId":columnId,
            pageSize: 10,
		};

        if (param) searchData={...searchData, ...param};

		$.ajax({
			type: "post",
			url: "{:url('index')}",
			dataType: "json",
			data: searchData,
			async:false,
			success: function (res) {
				if (res.code == 1 && res.data) {
					let data = res.data;
					let paginationData = {
						pageSize: data.per_page,
						total: data.total,
						currentPage: data.current_page
					};
					initTable(paginationData, data.data);
				}
                $('#loadingContainer').removeClass('loading-container');
			}, error: function (res) {
                $('#loadingContainer').removeClass('loading-container');
			}
		});
	}

	/**
	 * @description: 初始化表格
	 * @param {*} pageSize
	 * @param {*} total
	 * @param {*} currentPage
	 * @param {*} dataList
	 * @return {*}
	 * @Date: 2022-01-12 10:55:11
	 */
	function initTable({ pageSize, total, currentPage }, dataList) {
		if (dataList == undefined){
			dataList = [];
		}
		if(total == undefined){
			total = 0;
		}
		// 追加表格 html
		_appendToTable(dataList);

        // 分页
        foxui.pagination(
            {
                el: '#pagination',
                currentPage: currentPage,
                total: total,
                onchange: function ({ currentPage, pageSize, total }, callback) {
                    callback({ total, pageSize, currentPage });
                    $('#loadingContainer').addClass('loading-container');
                    init({pageSize, currentPage});
                },
            },
            {
                type: 'plain',
                isShowJump: true,
                isShowTotal: true,
                isShowSize: true,
                pageSize: pageSize
            }
		);

		//总数
		$(".right.total").empty().html("共" + total + "条记录");
	}

	/**
	 * @description: 追加表格 html
	 * @param {*} dataList
	 * @return {*}
	 * @Date: 2022-01-12 00:18:40
	 */
	function _appendToTable(dataList) {
		const html = _trsHtml(dataList);
		$('.foxui-table-tbody').empty().append(html);
	}

	/**
	 * @description: 表格 html
	 * @param {*} dataList
	 * @return {*}
	 * @Date: 2022-01-12 00:18:52
	 */
	function _trsHtml(dataList) {
		let htmlArr = [];
		let tableItemStr = $("#tableItemStr").val();
		let tableItem = [];//表项
		if(tableItemStr.length > 0){
			tableItem = tableItemStr.split(",");
		}
		dataList.forEach(item => {
			let fieldHtml = [];//拼装字段值
			$.each (tableItem, function(k,v){
				if(v != "id"){
					fieldHtml.push(`<div class="foxui-table-td"><span class="foxui-ellipsis-2">${item[v]}</span></div>`);
				}
			})
			htmlArr.push(`
            <li class="foxui-table-tr">
                <div class="foxui-table-td" style="flex: initial; width: 40px">
                    <div class="foxui-checkbox">
                        <span class="foxui-checkbox-input">
                            <i class="foxui-checkbox-icon"></i>
                            <input type="checkbox" value="" />
                        </span>
                    </div>
                </div>
                <div class="foxui-table-td">${item.id}</div>
				${fieldHtml.join("")}
                <div class="foxui-table-td">
                    <button class="foxui-text-primary foxui-size-medium delete-btn" id="${item.id}" onclick="deleteItem(event)">删除</button>
                    <button class="foxui-text-primary foxui-size-medium delete-btn" id="${item.id}" onclick="detailItem(event)">详情</button>
                </div>
            </li>
        `);
		});
		return htmlArr.join('');
	}

	// let bind_form = "{$bind_form}";
	let bind_form = $('input[name="bind_form"]').val();
	if(bind_form == 1){
		init();
	}
	//搜索
	$(".search-btn").on('click', function() {
		init();
	});

	//详情
	function detailItem(event){
		let obj = $(event.target);
		let isBtn = $(obj).is('button');//判断是否为button标签
		if(!isBtn){
			obj = $(obj).parent('button');
		}
		let id = $(obj).attr("id");
		window.location.href="{:url('form/FormList/detail')}" + '?id=' + id  + '&type=1' + '&formListId='+ formListId;
	}

	//单向删除
	function deleteItem(event) {
		let obj = $(event.target);
		let isBtn = $(obj).is('button');//判断是否为button标签
		if(!isBtn){
			obj = $(obj).parent('button');
		}
		let id = $(obj).attr("id");
		foxui.dialog({
			title: '删除',
			content: '您确定要删除吗?',
			cancelText: '取消',
			confirmText: '删除',
			buttonType: 'danger',
			confirm: function(callback) {
				foxui.closeLoading();

				$.ajax({
					type: "post",
					url: "{:url('form/FormList/lookDeletes')}",
					dataType: "json",
					data:{"idList":JSON.stringify([id]), "formListId": formListId},
					success: function(res) {
						foxui.closeLoading();
						if (res.code == 1) {
							foxui.message({
								text: res.msg,
								type: 'success',
							});
							init();
						} else {
							foxui.message({
								text: res.msg,
								type: 'error',
							});
						}
					},
					error: function(res) {
						foxui.closeLoading();
						foxui.message({
							text: res.msg,
							type: 'info',
						});
					}
				});
				callback();
			},
			cancel: function() {
				foxui.message({
					message: '取消删除',
					type: 'info'
				});
			},
		});

	}

	// 多选删除
	$('.table-footer .delete-btn').click(function () {
		let $isChecked = $('.foxui-table-td .foxui-checkbox.is-checked'),
				$checkedTr = $isChecked.closest('.foxui-table-tr'),
				len = $isChecked.length,
				idList = [];

		if (len < 1) {
			foxui.message({
				text: '请先选译要删除的数据！',
				type: 'danger',
			});
		} else {
			foxui.dialog({
				title: '确认',
				content: '您确定要删除选中的所有数据吗？',
				confirmText: '删除',
				cancelText: '取消',
				buttonType: 'danger',
				buttonSize: 'small',
				confirm: function (callback) {
					// 异步删除数据
					$checkedTr.each(function () {
						let id = $(this).find('.foxui-table-td:nth-child(2)').text();
						idList.push(id);
					});
					$.ajax({
						type: "post",
						url: "{:url('form/FormList/lookDeletes')}",
						dataType: "json",
						data: {
							"idList": JSON.stringify(idList),
							"formListId": formListId
						},
						success: function(res) {
							if (res.code == 1) {
								foxui.message({
									text: res.msg,
									type: 'success',
								});

								init();
							}else{
								foxui.message({
									text: res.msg,
									type: 'warning',
								});
							}
						},
						error: function(res) {
							foxui.message({
								text: res.responseJSON.msg,
								type: 'warning',
							});
						}
					});
					callback();
				},
			});
		}
	});
</script>

{/block}
